package com.alpha.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.apache.log4j.Logger;

import com.alpha.dao.interfaces.DataAccessObject;

public abstract class AlphaDao implements DataAccessObject {
	protected Connection connection;
	protected Statement statement;
	protected PreparedStatement preparedStatement;
	protected ResultSet resultSet;
	protected static Logger logger = Logger.getLogger(AlphaDao.class.getName());

	@Override
	public void connect() throws NamingException, SQLException {
		try {
			Context context = new InitialContext();
			DataSource ds = (DataSource) context
					.lookup("java:comp/env/jdbc/alpha");
			connection = ds.getConnection();
		} catch (NamingException e) {
			logger.error(e.getMessage());
			throw e;
		} catch (SQLException e) {
			logger.error(e.getMessage());
			throw e;
		}
	}

	@Override
	public void disconnect() throws SQLException {
		if (this.resultSet != null) {
			try {
				this.resultSet.close();
			} catch (SQLException e) {
				logger.error(e.getMessage());
				throw e;
			}
		}
		if (this.preparedStatement != null) {
			try {
				this.preparedStatement.close();
			} catch (SQLException e) {
				logger.error(e.getMessage());
				throw e;
			}
		}
		if (this.statement != null) {
			try {
				this.statement.close();
			} catch (SQLException e) {
				logger.error(e.getMessage());
				throw e;
			}
		}
		if (this.connection != null) {
			try {
				this.connection.close();
			} catch (SQLException e) {
				logger.error(e.getMessage());
				throw e;
			}
		}
	}

	public Connection getConnection() {
		return connection;
	}

	public void setConnection(Connection connection) {
		this.connection = connection;
	}

	public Statement getStatement() {
		return statement;
	}

	public void setStatement(Statement statement) {
		this.statement = statement;
	}

	public PreparedStatement getPreparedStatement() {
		return preparedStatement;
	}

	public void setPreparedStatement(PreparedStatement preparedStatement) {
		this.preparedStatement = preparedStatement;
	}

	public ResultSet getResultSet() {
		return resultSet;
	}

	public void setResultSet(ResultSet resultSet) {
		this.resultSet = resultSet;
	}

}
